package br.usp.icmc.client.main;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;

import br.usp.icmc.client.controladores.ControllerClient;
import br.usp.icmc.client.controladores.ControllerInquiry;
import br.usp.icmc.client.controladores.ControllerKeyWord;
import br.usp.icmc.client.controladores.ControllerLogin;
import br.usp.icmc.client.controladores.ControllerProvider;
import br.usp.icmc.client.controladores.ControllerService;
import br.usp.icmc.client.dao.KeyWordDAO;
import br.usp.icmc.client.dao.ServiceDAO;
import br.usp.icmc.client.entidades.KeyWord;
import br.usp.icmc.client.entidades.Service;
import br.usp.icmc.client.util.*;

/***********************************************************
 * 
 * <b> <br> Projeto: Aplicativo Cliente <br><b>
 * 
 * Classe que executa os comandos da aplicação
 * 
 * @author felipe
 *
 ***********************************************************/

public class Terminal {
	Runtime run = Runtime.getRuntime();
	Process p;
	//ControllerLogin controllerLogin = new ControllerLogin();
	//ControllerProvider controllerProvider = new ControllerProvider();
	ControllerClient controllerClinet = new ControllerClient();
	ControllerInquiry controllerInquiry = new ControllerInquiry();
	ControllerService controllerService = new ControllerService();
	Util util = new Util();
	ServiceDAO serviceDAO = new ServiceDAO();
	
	private String command;
	private String projectName;
	private List l;
	private Iterator it;
	private KeyWord word;
	private Service service;
	private List<String> palavrasChave;
	String home = System.getProperty("user.home");
		
	public String getProjectName() {
		return projectName;
	}

	public void setProjectName(String projectName) {
		this.projectName = projectName;
	}

	public String getCommand() {
		return command;
	}

	public void setCommand(String command) {
		this.command = command;
	}

	/**
	 * Detalha o serviço
	 * 
	 * @param name
	 */
	public void viewService(String name){
		l = controllerService.serviceByName(name);
		
		if(!l.isEmpty()){
			it = l.iterator();
			while(it.hasNext()){
				service = (Service) it.next();
			}
			
			List aux = controllerService.serviceKw(service.getIdService());
			Iterator ite = aux.iterator();
			while(ite.hasNext()){
				word = (KeyWord) ite.next();
			}
			
			
		System.out.println(">>> Service ID: " + service.getIdService());
		System.out.println(">>> Service Name: "+ service.getName());
		System.out.println(">>> Service Endpoint: " + service.getEndPoint());
		System.out.println(">>> Service Version " + service.getVersion());
		System.out.println(">>> Service License: " + service.getLicense());
		System.out.println(">>> Service Descrition: " + service.getDescription());
		System.out.println(">>> Service Type: " + word.getWord());
		} else {
			System.out.println("No service was found");
		}
	}
	
	/**
	 * Mostra os projetos no workspace do usuário
	 * 
	 * @param objLogin
	 */
	public void showProjects(Login objLogin){
		try {
			p = run.exec("ls " + objLogin.getPath());
			String stdIn = "", stdErr = "", s;
			
			BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
			
			while ((s = stdInput.readLine()) != null) {
                stdIn += s + "\n";
            }
			
			 System.out.println(stdIn);
			
		} catch (IOException e) {
			System.out.println("Error!");
		}
	}
	
	/**
	 * Carrega um projeto
	 * 
	 * @param projectName
	 */
	public void loadProject(String projectName){
		setProjectName(projectName);
	}	
	
	/**
	 * Baixa o serviço na pasta do projeto do cliente
	 * 
	 * @param objLogin
	 * @param name
	 */
	public void getService(Login objLogin, String name){		
		
		String pathService;
		
		if(getProjectName().isEmpty()){
			pathService = objLogin.getPath();
		} else {
			pathService = objLogin.getPath() + getProjectName();
		}
		
		//String pathService = objLogin.getPath() + getProjectName();
		File dir = new File(pathService);
		String endPoint = null;
		
		l = controllerService.serviceByName(name);
		
		if(!l.isEmpty()){
			it = l.iterator();
			while(it.hasNext()){
				Service service = (Service) it.next();
				endPoint = service.getEndPoint();
			}
			
			try {
				if(endPoint.contains("git")){
					setCommand("git clone "+endPoint);			
				} else if(endPoint.contains("svn")){
					setCommand("svn checkout "+endPoint);
				}
				
				run.exec(getCommand(), null, dir);
				System.out.println("The service has been downloaded.");
			} catch (IOException e) {
				System.out.println("Error: Service not downloaded");
			}
			
		} else {
			System.out.println("No service was found");
		}
		
				
	}
	
	/**
	 * 
	 * 
	 */
	public void currentProject(){
		System.out.println(getProjectName());
	}
	
	/*
	public void createProject(String projectName){
		command = "catkin_create_pkg "+projectName;
		File file = new File("/home/felipe/catkin_ws/src");
		ProcessBuilder pb = new ProcessBuilder(command);
		pb.environment().put("path", "~/catkin_ws/src/pessegoROS");
		try {
			Process p = pb.start();
			p.destroy();
		} catch (IOException e1) {
			System.out.println("falhou miseravelmente");
		}
		
	}*/
	
	public void buildPackage() {
		setCommand("cmake ../src");
		String path = "/home/felipe/catkin_ws/build";
		File dir = new File(path);
		//File directory = new File(home+"/catkin_ws/");
		String stdIn = "", stdErr = "", s;
		
		try {
			Process p = run.exec(getCommand(), null, dir);
			
			BufferedReader stdInput = new BufferedReader(new
					InputStreamReader(p.getInputStream()));
			
			BufferedReader stdErro = new BufferedReader(new
					InputStreamReader(p.getErrorStream()));
			
			while((s = stdInput.readLine()) != null){
				stdIn += s + "\n";
			}
		
			while((s = stdErro.readLine()) != null){
				stdErr += s + "\n";
			}
		
			System.out.println("saida: \n" + stdIn);
			System.out.println("erro: \n" + stdErr);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println(e);
		}
		
		
		
		
		//ProcessBuilder processBuilder = new ProcessBuilder(command);
		//File directory = new File(home+"/catkin_ws/");
		//processBuilder.directory(directory);
		/*
		try {
			Process process = processBuilder.start();
			process.waitFor();
			System.out.println("processo terminado");
		} catch (IOException e) {
			System.out.println("Erro Miseravel");
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			System.out.println("interrompido");
		}*/
		
	}
	
	public void createDirectory(Login objLogin, String projectName){
			
		File dir = new File(objLogin.getPath()+projectName);
		if(dir.mkdir()){
			setProjectName(projectName);
			System.out.println("Project \033[0m"+getProjectName()+" \033[0mcreated successfully");
		} else {
			System.out.println("Error: Project not created!");
		}
		
	}
	
	public void findByWord(String type){
			l = serviceDAO.selectServiceWord(type);
			
			if(!l.isEmpty()){
				//util.limparTela();
				it = l.iterator();
				System.out.printf(">>> %-30s %-30s %-30s\n", "Name", "Provider", "Type");
				while(it.hasNext()){
					Service service = (Service) it.next();
					//System.out.println(">>> " +service.getName());
					List aux = controllerService.serviceKw(service.getIdService());
					Iterator ite = aux.iterator();
					while(ite.hasNext()){
						word = (KeyWord) ite.next();
					}
					
					System.out.printf(">>> %-30s %-30s %-30s\n", service.getName(), service.getEmailProvider(), word.getWord());				
				}
			} else {
				System.out.println("No service was found");
			}		
		
	}
	
	public void findName(String name){
		
		l = controllerInquiry.searchByName(name);
		if(!l.isEmpty()){
			//util.limparTela();
			it = l.iterator();
			System.out.printf(">>> %-30s %-30s %-30s\n", "Name", "Provider", "Type");
			while(it.hasNext()){
				Service service = (Service) it.next();
				
				List aux = controllerService.serviceKw(service.getIdService());
				Iterator ite = aux.iterator();
				while(ite.hasNext()){
					word = (KeyWord) ite.next();
				}
				
				
				
				System.out.printf(">>> %-30s %-30s %-30s\n", service.getName(), service.getEmailProvider(), word.getWord());			
			}
		} else {
			System.out.println("No service was found");
		}
	}
	
	public void findAll(){
		ControllerInquiry controllerInquiry = new ControllerInquiry();
		
		l = controllerInquiry.searchAll();
		if(!l.isEmpty()){
			//util.limparTela();
			it = l.iterator();
			System.out.printf(">>> %-30s %-30s %-30s\n", "Name", "Provider", "Type");
			while(it.hasNext()){
				Service service = (Service) it.next();
				//System.out.println(">>> " +service.getName());
				List aux = controllerService.serviceKw(service.getIdService());
				Iterator ite = aux.iterator();
				while(ite.hasNext()){
					word = (KeyWord) ite.next();
				}
				
				System.out.printf(">>> %-30s %-30s %-30s\n", service.getName(), service.getEmailProvider(), word.getWord());
			
			}
		} else {
			System.out.println("No service was found");
		}
	}
	
	public void clear(){
		util.limparTela();
	}
	
	public void help(){
		System.out.println(">>> **********************************************************************");
		System.out.println(">>> rss find-all -> Return all services");
		System.out.println(">>> rss find-name [arg] -> Return the services by a chosen name");
		System.out.println(">>> rss find-type [arg] -> Return the services by a chosen type");
		System.out.println(">>> rss show -> Return the Types of Service presents on the Repository");
		System.out.println(">>> rss view [arg] -> Return details about a chosen service");
		System.out.println(">>> rss get-service [arg] -> Get the service");
		System.out.println(">>> rss create-project [arg] -> Create a ROS Project");
		System.out.println(">>> rss load-project [arg] -> Load a ROS Project");
		System.out.println(">>> rss show-projects -> Show your ROS Projects");
		System.out.println(">>> rss current-project -> Show your current project");
		System.out.println(">>> rss exit -> Close the app.");
		System.out.println(">>> **********************************************************************");
	}
	
	public void exit(){
		System.exit(0);
	}
	
	public void show(){
		KeyWordDAO keywordDAO = new KeyWordDAO();
		
		l = keywordDAO.selectAllWord();
		if(!l.isEmpty()){
			//util.limparTela();
			it = l.iterator();
			while(it.hasNext()){
				KeyWord word = (KeyWord) it.next();
				
				String[] split = word.getWord().split("-");
				
				int blankSpaces = word.getWord().length() - split[split.length - 1].length();
				
				
				StringBuilder sb = new StringBuilder();
				for(int i = 0; i < blankSpaces; i++){
					sb.append(" ");
				}				
				System.out.println(">>>"+sb+split[split.length - 1]);
			}
		} else {
			System.out.println("No service type was found");
		}		
	}
	

}
